<?php
namespace frontend\controllers;

use Yii;
use yii\db\Query;
use common\models\Category;
use common\models\Product;
use common\models\ProductCategory;
use common\models\Post;
use common\models\Brand;
use common\models\Banner;
use common\models\Order;
use yii\helpers\ArrayHelper;

/**
 * Index controller
 */
class IndexController extends FController
{

 public $enableCsrfValidation = false;
    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        //$this->getView()->title = $this->w_config['website_name'];
      
        $cache = Yii::$app->cache;

        $uid = Yii::$app->user->id;
        //订单状态统计
        $count = [];
        if($uid){
            for ($i=1; $i <4 ; $i++) { 
                $num = (new \Yii\db\Query())
                        ->select('count(id)')
                        ->from('order')
                        ->where(['user_id'=>$uid,'order_status'=>$i])
                        ->scalar();
                $count[$i]['num'] = $num;
                $count[$i]['name'] = Order::itemAlias('order_status',$i);
            }
        }


        //首页分类显示查询
        $category_1 = $cache->get('category_1');

        if ($category_1 === false) {

            $category_1=Category::find()
                    ->where(['level'=>1,'parent_id'=>0,'is_show'=>1])
                    ->select('name,id,parent_id')
                    //->limit(3)
                    ->orderby('sort_number asc,id asc')
                    ->asArray()
                    ->all();
            foreach ($category_1 as $key => $value) {
                $category_1[$key]['cate_list'] = Category::find()
                        ->select('name,id,parent_id')
                        ->where(['level'=>2,'parent_id'=>$value['id'],'is_show'=>1])
                        //->limit(8)
                        ->orderby('sort_number,id')
                        ->asArray()
                        ->all();
                /*foreach ($category_1[$key]['list'] as $k => $v) {
                    $category_1[$key]['list'][$k]['list'] = Category::find()
                        ->select('name,id,parent_id')
                        ->where(['level'=>3,'parent_id'=>$v['id'],'is_show'=>1])
                        ->asArray()
                        ->all();
                }*/
            }
            foreach ($category_1 as $key => $value) {
                $need_id_list =Productcategory::find() //sum(d.product_num),
                    ->select('b.id,b.name,b.title,b.img_url,b.product_price,b.price_unit,b.spec,b.sort_numer,c.order_id')
                    ->where(['in', 'category_id',  ArrayHelper::getColumn($value['cate_list'],'id')])
                    ->andwhere('b.is_show = 1')
                    ->leftJoin('product AS b','b.id = product_category.product_id')
                    ->leftJoin('order_product AS c','b.id = c.product_id')
                    ->orderBy('b.hot_sort,b.sort_numer asc,b.id desc')
                    ->asArray()
                    ->all();
                $category_1[$key]['pro_list'] = [];
                if($need_id_list){
                    $category_1[$key]['pro_list'] = $need_id_list;
                }
                foreach ($category_1[$key]['pro_list'] as $k => $v) {

                    $category_1[$key]['pro_list'][$k]['sale_sum'] = 0;
                    $category_1[$key]['pro_list'][$k]['sale_user'] = 0;

                    if($v['order_id']){
                        $count_sum = (new \Yii\db\Query)
                                ->select('sum(b.product_num),count(a.id)')
                                ->from('order_product a')
                                ->where(['a.product_id' => $v['id'],'b.order_status'=>4,'b.pay_status'=>2,'b.shipping_status'=>3])
                                ->leftJoin('order AS b','b.id = a.order_id')
                                ->one();
                        $category_1[$key]['pro_list'][$k]['sale_sum'] = $count_sum['sum(b.product_num)'];
                        $category_1[$key]['pro_list'][$k]['sale_user'] = $count_sum['count(a.id)'];
                    }
                    unset($category_1[$key]['pro_list'][$k]['order_id']);
                }
            }
            $cache->set('category_1', $category_1);
        }
        
        // 尝试从缓存中取回 $data 
        $brand_list = $cache->get('brand_list');

        if ($brand_list === false) {

            //查询品牌、
            $brand_list = Brand::find()->select('id,name')->where(['is_show'=>1])->asArray()->all();
            $cache->set('brand_list', $brand_list);
        }
        
        //增加点击量
        $co=Yii::$app->request->post('name');
        $link=Yii::$app->request->post('link');
        $db = Yii::$app->db;
        if($co && $link){
             $sql = "UPDATE banner SET click_count=click_count+1 where id='$co'";
             $db->createCommand($sql)->execute();
            return $link;
        }
         //查询轮播广告
        $ban = $cache->get('banner');
        if ($ban === false) {
            $banner=Banner::find()
                    ->select('id,name,img_url,link,width,height,target')
                    ->where(['pid'=>1,'enabled'=>1])
                    ->limit(8)
                    ->asArray()
                    ->orderBy('orderBy asc')
                    ->all();
                    //$banne = array ();
            foreach ($banner as $k => $value)
            {
                $ban[] = array (
                    'id' => $value['id'],
                    'name' => $value['name'],
                    'link' => $value['link'],
                    'img_url' => $value['img_url'],
                    'width' => $value['width'],
                    'height' => $value['height'],
                    'target' => $value['target'],
                );
            }
            $cache->set('banner',$ban);
        }
        //首页公告显示查询
        $notice=Post::find()
                ->where(['post_category_id'=>6,'status'=>1])
                ->orderBy('id desc')
                ->limit(4)
                ->all();
 
        return $this->render('index',[
            'notice' => $notice,
            'category_1' => $category_1,
            'brand_list' => $brand_list,
            'ban' =>$ban,
            'count' => $count
        ]);
    }
     
    public function excel(){
        //phpexcel导出功能示例

       /* $title = '分类表';
        $expFileName='分类表';          
        $expCellName = array(
            array('id','编号'),
            array('name','名称'),
            array('pinyin_name','拼音'),
            array('is_show','是否显示'),
            array('create_time','创建时间'),
            array('update_time','更新时间')
        );
        $expTableData = Category::getList();

        $do=exportExcel($title.date('Ymd'),$expFileName,$expCellName,$expTableData);*/
    }

    /**
     * 清除缓存
     * @return [type] [description]
     */
    public function actionClear(){
        Yii::$app->cache->flush();
    }
}

